import { getInfo } from '@/api/user'
import { login } from '@/api/login'

const state = {
  userInfo: null
}
const mutations = {
  // 设置个人信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = null
  }

}
const actions = {
  // 登录
  Login(context, userInfo) {
    console.log('=============================',userInfo)
    const username = userInfo.username.trim()
    const password = userInfo.password
    return new Promise((resolve, reject) => {
      login(username, password).then(res => {
        // let data = res.data
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 封装获取token的登录action
  getUserInfo(context, data) {
    // 一旦涉及到promise的封装, 不要用async await, 请用.then .catch
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const newUserInfo = res.data
        context.commit('setUserInfo', newUserInfo)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getUserInfo1(context, data) {
    // 一旦涉及到promise的封装, 不要用async await, 请用.then .catch
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const newUserInfo = res.data
        context.commit('setUserInfo', newUserInfo)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  removeUserInfo(context) {
    context.commit('removeUserInfo')
  }

}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
